<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title>募捐详情</title>
    <link rel="stylesheet" href="../../element/element.css">
    <script src="../../element/vue.js"></script>
    <script src="../../element/index.js"></script>
    <script src="../../js/axios.min.js"></script>
</head>

<link rel="stylesheet" type="text/css" href="../../css/dontions.css">

<body>

    <body>
        <div id="app">
            <el-card>
                <el-button type="primary" @click="save()">返回</el-button>
                <el-dialog title="修改募捐信息" :visible.sync="editFormVisible">
                    <el-form :model="editForm" label-width="100px">
                        <el-form-item label="化名">
                            <el-input v-model="editForm.alias"></el-input>
                        </el-form-item>
                        <el-form-item label="年龄">
                            <el-input v-model="editForm.age"></el-input>
                        </el-form-item>

                        <el-form-item label="目标金额">
                            <el-input v-model="editForm.donationAmount"></el-input>
                        </el-form-item>
                        <el-form-item label="募捐金额原因">
                            <el-input v-model="editForm.amountReason"></el-input>
                        </el-form-item>
                        <el-form-item label="截止日期">
                            <el-input v-model="editForm.deadline"></el-input>
                        </el-form-item>
                        <el-form-item label="募捐时间原因">
                            <el-input v-model="editForm.timeReason"></el-input>
                        </el-form-item>
                        <el-form-item label="上传头像">
                            <el-upload action="" :show-file-list="false" :on-change="handleAvatarChange"
                                :auto-upload="false">
                                <el-button size="small" type="primary">点击上传</el-button>
                            </el-upload>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" @click="submitEditForm">保存</el-button>
                            <el-button @click="editFormVisible = false">取消</el-button>
                        </el-form-item>
                    </el-form>
                </el-dialog>

                <el-dialog title="编辑募捐详情" :visible.sync="editDialogVisible">
                    <el-form :model="editForm2" label-width="80px">
                        <el-form-item label="申请缘由:">
                            <el-input v-model="editForm2.incident"></el-input>
                        </el-form-item>
                        <el-form-item label="家庭情况:">
                            <el-input v-model="editForm2.family"></el-input>
                        </el-form-item>
                        <el-form-item label="财务状况:">
                            <el-input v-model="editForm2.finance"></el-input>
                        </el-form-item>
                        <el-form-item label="预期目标:" label-width="90px">
                            <el-input v-model="editForm2.status"></el-input>
                        </el-form-item>
                    </el-form>
                    <div slot="footer" class="dialog-footer">
                        <el-button @click="editDialogVisible = false">取 消</el-button>
                        <el-button type="primary" @click="submitEdit">确 定</el-button>
                    </div>
                </el-dialog>

                <div style="display: flex; justify-content: center; align-items: center;">
                    <h2 slot="header">募捐详情</h2>
                </div>

                <div v-for="detail in donationDetails" :key="detail.id">
                    <el-row>
                        <el-col :span="12">
                            <img :src="`http://${detail.donationImage}`" alt="募捐图片" width="300px" height="300px">
                            <p>&nbsp&nbsp&nbsp别名：{{ detail.alias }}&nbsp&nbsp&nbsp年龄：{{ detail.age }} </p>
                        </el-col>
                        <el-row style="position: absolute;  right: 20px;">
                            <i :class="getDonationIconClass(donationDetails[0].status)">
                                {{ getDonationStatus(donationDetails[0].status) }}</i>
                        </el-row>
                        <p>目标金额：{{ detail.donationAmount }}</p>
                        <p>募捐金额原因：{{ detail.amountReason }}</p>
                        <p>截止日期：{{ detail.deadline }}</p>
                        <p>募捐时间原因:{{ detail.timeReason }}</p>
                        </el-col>
                    </el-row>
                    <el-button type="primary" @click="showEditForm(detail)">修改募捐基本信息</el-button>
                </div>
                <el-row v-if="donationsInfo">
                    <el-col :span="24">
                        <p>申请缘由：{{ donationsInfo.incident }}</p>
                        <p>家庭情况：{{ donationsInfo.family }}</p>
                        <p>财务状况：{{ donationsInfo.finance }}</p>
                        <p>预期目标：{{ donationsInfo.status }}</p>
                    </el-col>
                </el-row>

                <el-row v-if="donationsInfo">
                    <el-col :span="24">
                        <el-button type="primary" @click="showEditDialog">编辑募捐详细信息</el-button>
                    </el-col>
                </el-row>
                <el-table :data="pointsList" style="width: 100%" @selection-change="onSelectionChange">
                    <!-- 选择列 -->
                    <el-table-column v-if="showSelection" type="selection"></el-table-column>

                    <!-- 其他列 -->
                    <el-table-column prop="pointsRulesId" label="ID"></el-table-column>
                    <el-table-column prop="ruleTitle" label="标题"></el-table-column>
                    <el-table-column prop="pointsValue" label="分值"></el-table-column>
                    <el-table-column prop="details" label="具体描述"></el-table-column>
                </el-table>

                <!-- 提交按钮 -->
                <el-button v-if="showSelection" type="primary" @click="handleSubmit">提交</el-button>
                <el-button v-if="!showSelection" type="primary" @click="redact">编辑</el-button>

                <!-- 总分 -->
                <p v-if="showSelection">总分: {{ totalPoints }}</p>
                <p v-if="!showSelection">总分: {{TotalPoints}}</p>
                <el-row class="flex-container">
                    <el-row class="buttons">
                        <el-col>
                            <el-button type="primary" icon="el-icon-s-operation" @click="downloadDataTemplate">
                                下载募捐资料模板
                            </el-button>

                            <el-button type="primary" icon="el-icon-upload2" @click="upload">
                                上传募捐资料
                            </el-button>
                            <input type="file" ref="file" v-show="false" @change="handleFileUpload" />

                            <el-button type="primary" icon="el-icon-download" @click="getdonationIdFile">
                                下载募捐资料
                            </el-button>
                        </el-col>
                    </el-row>
                </el-row>

                <br>
                <el-button type="primary" @click="save()">保存并退出</el-button>
                <el-button type="primary" @click="submitDonations()">提交</el-button>
                <el-button type="primary" @click="revokeDonations()">撤回</el-button>

        </div>

        <script>
            var DonationId = localStorage.getItem('donationId');
            new Vue({
                el: '#app',
                data() {
                    return {
                        pointsId:"",
                        showSelection: false,
                        isPointsRules: "",
                        pointsList: [], // 积分列表数据
                        selectedRows: [], // 选择的行数据
                        totalPoints: 0, // 总分
                        isExpenseTableVisible: false,
                        isTableVisible: false,
                        donationsInfo: null,
                        donationRecords: [],
                        fundingDetails: [],
                        editFormVisible: false,
                        editForm: {
                            alias: '',
                            age: 0,
                            // 其他字段略
                        },
                        editDialogVisible: false,
                        editForm2: {
                            incident: '',
                            family: '',
                            finance: '',
                            status: ''
                        },
                        donationDetails: [],
                    }
                },
                watch: {
                    selectedRows: {
                        handler: function (newRows, oldRows) {
                            this.totalPoints = 0; // 每次选择发生变化时先重置总分
                            newRows.forEach(row => {
                                this.totalPoints += row.pointsValue;
                            });
                        },
                        deep: true // 深度监听数组内部对象的变化
                    }
                },
                methods: {
                    showReportForm() {
                    this.reportFormVisible = true;
                },
                
                    redact() {
                        this.showSelection = !this.showSelection;
                        axios.get('http://localhost:8888/api/donation/getPoints', {
                            params: {
                                pointsId: this.pointsId// 替换为实际的pointsId值
                            }
                        })
                            .then(response => {
                                const result = response.data;
                                if (result.code === 0) {
                                    this.pointsList = result.data;
                                } else {
                                    console.error(result.message);
                                    console.log("查询失败");
                                }
                            })
                            .catch(error => {
                                console.error(error);
                                // 处理错误的逻辑...
                            });
                    },
                    search() {
                        axios.get('http://localhost:8888/api/donation/getByIsPointsRules', {
                            params: {
                                isPointsRules: this.isPointsRules
                            }
                        })
                            .then(response => {
                                const result = response.data;
                                if (result.code === 0) {
                                    this.pointsList = result.data;
                                } else {
                                    console.error(result.message);
                                    console.log("查询失败");
                                }
                            })
                            .catch(error => {
                                console.error(error);
                                // 处理错误的逻辑...
                            });
                    },
                    handleSubmit() {
                        const selectedIds = this.selectedRows.map(row => row.pointsRulesId);
                        const params = {
                            donationId: DonationId,
                            isPointsRules: selectedIds.join(',')
                        };

                        axios.post('http://localhost:8888/api/donation/setPointsRule', params)
                            .then(response => {
                                // 请求成功处理逻辑
                                const { code, message, data } = response.data;
                                if (code === 0) {
                                    console.log(message);
                                    console.log(data);
                                    this.showSelection = !this.showSelection
                                    this.isPointsRules = selectedIds.join(',')
                                    this.search()
                                    alert("提交成功")
                                } else {
                                    console.error('请求失败');
                                }
                            })
                            .catch(error => {
                                // 请求失败处理逻辑
                                console.error('请求出错', error);
                            });
                    },
                    // 选择行发生变化时触发
                    onSelectionChange(rows) {
                        this.selectedRows = rows; // 将选中的行数据赋值给 selectedRows 变量
                        this.totalPoints = 0; // 每次选择发生变化时先重置总分
                        this.selectedRows.forEach(row => {
                            this.totalPoints += row.pointsValue;
                        });
                    },
                    save() {
                        window.location.href = "donationManger.html"
                    },
                    //状态样式选择
                    getDonationIconClass(status) {
                        if (status === 1 || status === 3 || status === 5 || status === 6) {
                            return 'el-icon-circle-check';
                        } else if (status === 4) {
                            return 'el-icon-warning-outline';
                        } else {
                            return 'el-icon-circle-close';
                        }
                    },
                    //提交募捐申请
                    submitDonations() {
                        var self = this; // 存储 Vue 实例的引用
                        axios.post('http://localhost:8888/api/donation/submit', {
                            donationId: DonationId // 具体的募捐申请ID
                        })
                            .then(function (response) {
                                if (response.data.code === 0) {
                                    self.$message({
                                        message: response.data.message,
                                        type: 'success'
                                    });
                                    self.donationDetails[0].status = response.data.data.status;
                                } else {
                                    // 提示用户修改失败
                                    self.$message.error('提交失败，请刷新后重试');
                                }

                            })
                            .catch(function (error) {
                                // 请求失败时的处理
                                console.error('提交募捐申请失败：', error);
                            });
                    },
                    //撤回募捐申请
                    revokeDonations() {
                        var self = this; // 存储 Vue 实例的引用
                        axios.post('http://localhost:8888/api/donation/revoke', null, {
                            params: {
                                donationId: DonationId // 具体的募捐申请ID
                            },
                        })
                            .then(function (response) {
                                if (response.data.code === 0) {
                                    self.$message({
                                        message: response.data.message,
                                        type: 'success'
                                    });
                                    self.donationDetails[0].status = response.data.data.status;
                                } else {
                                    // 提示用户修改失败
                                    self.$message.error('撤回失败，请刷新后重试');
                                }
                            })
                            .catch(function (error) {
                                // 请求失败时的处理
                                console.error('提交募捐申请失败：', error);
                            });
                    },
                    //下半部分修改
                    showEditDialog() {
                        this.editForm2.incident = this.donationsInfo.incident;
                        this.editForm2.family = this.donationsInfo.family;
                        this.editForm2.finance = this.donationsInfo.finance;
                        this.editForm2.status = this.donationsInfo.status;
                        this.editDialogVisible = true;
                    },
                    //下半部分
                    submitEdit() {
                        axios.post('http://localhost:8888/api/donation/updateDetails', {
                            donationId: DonationId,
                            incident: this.editForm2.incident,
                            family: this.editForm2.family,
                            finance: this.editForm2.finance,
                            status: this.editForm2.status
                        })
                            .then(response => {
                                if (response.data.code === 0) {
                                    this.editDialogVisible = false;
                                    this.cancelSubmit(); // 刷新网页
                                    // 提示修改成功
                                    this.$message({
                                        message: '修改成功',
                                        type: 'success'
                                    });
                                } else {
                                    this.$message.error('系统繁忙，请稍后再试');
                                }
                            })
                            .catch(error => {
                                this.$message.error('请求失败: ' + error);
                            });
                    },
                    //刷新网页
                    cancelSubmit() {
                        location.reload()
                    },
                    //头像上传
                    handleAvatarChange(file) {
                        const donationId = this.editForm.donationId;
                        const formData = new FormData();
                        formData.append('donationId', donationId);
                        formData.append('file', file.raw);
                        axios.post('http://localhost:8888/api/donation/uploadDonationImage', formData)
                            .then(data => {
                                if (data.data.code === 0) {
                                    this.$message.success('头像上传成功');
                                    //更新头像显示
                                    this.avatarUrl = data.data.data
                                } else {
                                    this.$message.error(data.message);
                                }
                            })
                            .catch(error => {
                                this.$message.error('发生错误：' + error);
                            });
                    },
                    //上半点击修改
                    showEditForm(detail) {
                        this.editForm = { ...detail }; // 使用对象展开运算符将原始数据复制到编辑表单中
                        this.editFormVisible = true;
                    },
                    //上半点击保存
                    submitEditForm() {
                        console.log(this.editForm);
                        // 将原始日期字符串转换为Date对象
                        // const date = new Date(this.editForm.deadline);
                        // // 获取日期部分并转换为ISO格式
                        // const isoDate = date.toISOString().split('T')[0];
                        // // 获取时间部分并加上时区信息
                        // const isoTime = "16:00:00.000+00:00";
                        // // 拼接日期和时间部分
                        // this.editForm.deadline = `${isoDate}T${isoTime}`;
                        console.log(this.editForm.deadline);


                        axios.put('http://localhost:8888/api/donation/update', {
                            donationId: this.editForm.donationId,
                            alias: this.editForm.alias,
                            age: this.editForm.age,
                            deadline: this.editForm.deadline,
                            donationAmount: this.editForm.donationAmount,
                            timeReason: this.editForm.timeReason,
                            amountReason: this.editForm.amountReason,
                            status: this.donationDetails[0].status
                            // 其他字段略
                        })
                            .then(response => {
                                if (response.data.code === 0) {
                                    this.editFormVisible = false;
                                    // 提示用户修改成功
                                    this.$message.success('修改成功');
                                    // 重新获取募捐详情，刷新页面显示最新数据
                                    this.cancelSubmit();
                                } else {
                                    // 提示用户修改失败
                                    this.$message.error('修改失败，提交后不能进行修改');
                                }
                            })
                            .catch(error => {
                                console.error('请求失败:', error);
                                // 提示用户请求失败
                                this.$message.error('请求失败，请稍后重试');
                            });
                    },
                    //右上角状态显示
                    getDonationStatus(status) {
                        switch (status) {
                            case 1:
                                return '已保存';
                            case 2:
                                return '已删除';
                            case 3:
                                return '已提交';
                            case 4:
                                return '审核中';
                            case 5:
                                return '已发布';
                            case 6:
                                return '已完结';
                            default:
                                return '未知状态';
                        }
                    },
                    //获取募捐详情
                    getDonationDetails() {
                        axios.get('http://localhost:8888/api/donation/get', {
                            params: {
                                donationId: DonationId
                            }
                        })
                            .then(response => {
                                let data = response.data.data;
                                this.pointsId = response.data.data.pointsId;
                                this.isPointsRules = response.data.data.isPointsRules
                                if (data.deadline) {
                                    data.deadline = new Date(data.deadline).toLocaleDateString(); // 格式化为年月日
                                }
                                // log
                                this.donationDetails.push(data);
                                this.search()
                            })
                            .catch(error => {
                                console.error(error);
                            });
                        axios.get('http://localhost:8888/api/donation/getDonationsInfo', {
                            params: {
                                donationId: DonationId
                            }
                        })
                            .then(response => {
                                if (response.data.code === 0) {
                                    this.donationsInfo = response.data.data;
                                } else {
                                    console.error('Request failed: ' + response.data.message);
                                }
                            })
                            .catch(error => {
                                console.error('Request error: ' + error);
                            });
                        console.log(this.donationDetails);
                    },
                    //上传募捐资料
                    upload() {
                        this.$refs.file.click()
                    },
                    handleFileUpload() {
                        let file = this.$refs.file.files[0];
                        let donationId = DonationId; // 你需要从某个地方获取这个值

                        // 创建一个FormData对象
                        let formData = new FormData();
                        formData.append('donationId', donationId);
                        formData.append('file', file);

                        // 发送POST请求
                        axios.post('http://localhost:8888/api/donation/uploadData', formData, {
                            headers: {
                                'Content-Type': 'multipart/form-data'
                            }
                        }).then(response => {
                            if (response.data.code === 0) {
                                this.$message.success(response.data.message);
                            } else {
                                this.$message.error(response.data.message);
                            }
                        }).catch(error => {
                            console.log(error);
                            this.$message.error('上传失败');
                        });
                    },

                    //下载募捐资料
                    getdonationIdFile() {
                        fetch(`http://localhost:8888/api/donation/downloadData?donationId=${DonationId}`)
                            .then(response => response.blob())
                            .then(blob => {
                                const url = window.URL.createObjectURL(blob);
                                const link = document.createElement('a');
                                link.href = url;
                                link.setAttribute('download', 'dontionFile.pdf');
                                document.body.appendChild(link);
                                link.click();
                                document.body.removeChild(link);
                            })
                            .catch(error => {
                                this.$message.error("文件不存在");
                                console.error('Error downloading file:', error);
                                // 处理下载失败的情况
                            });
                    },
                    //下载募捐资料模板
                    downloadDataTemplate() {
                        axios.get('http://localhost:8888/api/points/download', {
                            responseType: 'blob',
                            params: {
                                pointsId: this.pointsId // 替换为您需要下载的文件对应的pointsId
                            }
                        })
                            .then(response => {
                                const url = window.URL.createObjectURL(new Blob([response.data]));
                                const link = document.createElement('a');
                                link.href = url;
                                link.setAttribute('download', 'points.doc');
                                document.body.appendChild(link);
                                link.click();
                                document.body.removeChild(link);
                                window.URL.revokeObjectURL(url);
                            })
                            .catch(error => {
                                console.error('下载失败', error);
                            });
                    }
                },

                computed: {
                    TotalPoints() {
                        return this.pointsList.reduce((total, item) => total + item.pointsValue, 0);
                    },
                    timestamp() {
                        return new Date().getTime();
                    }
                },
                created() {
                    // this.search(); // 页面加载时自动触发查询
                    this.getDonationDetails();
                }
            }
            );
        </script>
    </body>

</html>